package com.cross.plain;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import com.cross.core.AbstractWriter;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;
/**
 * 文本读取器
 * @author wu
 *
 */
public class SimplePlainWriter extends AbstractWriter {
	private Writer writer;
	private File file;
	private String split = ",";

	public SimplePlainWriter(Header header, File file) throws IOException {
		super.header = header;
		this.file = file;
		init();
	}

	public SimplePlainWriter(Header header, File file, String split)
			throws IOException {
		super.header = header;
		this.file = file;
		this.split = split;
		init();
	}

	private void init() throws IOException {
		writer = new FileWriter(file);
		StringBuffer sb = new StringBuffer();
		for (Column c : header.getColumns()) {
			sb.append(c.getTitle());
			sb.append(":");
			sb.append(c.getType());
			sb.append(split);
		}
		writer.write(sb.toString());
	}

	@Override
	protected void writeRow() {
		try {
			writer.write(split(currentRow));
			writer.write("/n/r");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String split(Row row) {
		StringBuffer sb = new StringBuffer();
		for (Item item : row.getItems()) {
			sb.append(item.getString());
			sb.append(",");
		}
		return sb.toString();
	}

	@Override
	public void close() {
		try {
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
